package com.dsc.download;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Path;

/**
 * @author: Du Shun Chang
 * @title: DownloadServlet
 * @date: 2022/2/5 19:47
 * @description: 文件下载demo
 * @version：1.0
 */
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.获取下载文件路径*/
        String realPath = this.getServletContext().getRealPath("/WEB-INF/img/me.jpg");
        System.out.println("文件下载路径为：" + realPath);
        /*2.获取文件下载名*/
       String fileName= realPath.substring(realPath.lastIndexOf("\\") + 1);
        /*3.浏览器支持下载的文件*/
        resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
    /*4.获取下载文件流*/
        FileInputStream inputStream = new FileInputStream(realPath);
        /*5.建立缓冲区*/
        int len =0;
        byte[] buffer=new byte[1024];
        /*6.获取outputstream对象*/
        ServletOutputStream outputStream=resp.getOutputStream();
        /*7.将FileOutputStream流写入到buffer缓冲区，使用outputStream将缓冲区的数据输出到客户端*/
        while ((len=inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
        }
        /*8.关闭资源*/
        inputStream.close();
        outputStream.close();
    }
}
